package com.gykfbxxh.imovie.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.utils.util.DateUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewFrameUtils;
import com.app.utils.util.ViewSizeUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.base.bean.DataBean;
import com.gykfbxxh.imovie.bean.comment.FilmComment;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.net.ParamMap;
import com.gykfbxxh.imovie.listener.CommentListener;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.manager.UserInforManager;

import java.util.HashMap;
import java.util.Map;


/**
 * 公用评论框dialog
 *
 * @author xuxinghai
 */
public class CommentUtils implements TextWatcher, OnClickListener, DialogUtils.OnDialogBtnClickListener {

    private Dialog dialog;// 评论dialog
    private EditText commentEdit;// 评论编辑框
    private TextView commentSend,tv_comment_cancel;// 发表评论按钮
    private View commentDialogView;// 评论框
    private String commentMsg;// edittext显示的默认字
    private Activity mActivity;


    private static CommentUtils mCommontUtils;
    private static Map<String, String> mCacheComStr;//缓存的评论内容
    private CommentListener mCommentListener;//评论监听
    private String newsId;//文章id
    private String mRrequestName;//网络请求标识
    private boolean isSaveComStr = true;//是否存储评论(评论成功就不存了)
    private String mCacheKey;//评论存储唯一键
    private static long mOldCommentTime;//上次评论的时间
    private static String mOldNewsid;//上一次发表的文章的id
    private static String mOldNewsComment;//上一次发表的文章的评论
    private View deleteView;
    private HashMap<String, Object> dialogParams;

    /**
     * 获取唯一实例
     *
     * @return CommentUtils
     */
    public static CommentUtils getInstance() {
        if (mCommontUtils == null) {
            mCommontUtils = new CommentUtils();
        }
        return mCommontUtils;
    }

    private CommentUtils() {
        mCacheComStr = new HashMap<String, String>();
    }


    /**
     * 展示评论弹窗
     *
     * @param activity
     * @param newsId   保存评论的唯一建
     */
    public void showDialog(Activity activity, String requestName, String newsId,CommentListener listener) {
        if (this.mActivity == activity) {
            //同一界面弹窗,则不用再初始化界面
            if (dialog == null) {
                initDialog();
            }
        } else {
            //如果不是同一界面则重新初始化dialgo
            this.mActivity = activity;
            initDialog();
        }
        if (dialog == null) {
            return;
        }
        //获取之前保存的评论
        if (mCacheComStr == null) {
            mCacheComStr = new HashMap<String, String>();
        }
        mCacheKey = newsId;
        String showStr = mCacheComStr.get(mCacheKey);
        //如果为空就不用适配表情了
        commentEdit.setText(showStr);
        commentEdit.setSelection(commentEdit.getText().length());
        //展示dialog
        if (mActivity != null && !mActivity.isFinishing() && dialog.getWindow() != null) {
            try {
                dialog.show();
                dialog.getWindow().setLayout(ViewSizeUtils.getWidthPixels(),
                        android.view.WindowManager.LayoutParams.WRAP_CONTENT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ViewFrameUtils.showSoftwareByView(commentEdit);
            //设置当前评论的数据
            this.mCommentListener = listener;
            this.newsId = newsId;
            this.mRrequestName = requestName;
        }
    }

    /**
     * 初始化dialog
     */
    private void initDialog() {
        if (mActivity == null) return;
        dialog = new Dialog(mActivity, R.style.CustomDialogStyle);
        commentDialogView = mActivity.getLayoutInflater().inflate(R.layout.dialog_comment_edit, null);
        commentEdit = (EditText) commentDialogView.findViewById(R.id.et_comment_msg);
        commentSend = (TextView) commentDialogView.findViewById(R.id.tv_comment_send);
        tv_comment_cancel = (TextView) commentDialogView.findViewById(R.id.tv_comment_cancel);
        commentEdit.addTextChangedListener(this);
        commentSend.setOnClickListener(this);
        tv_comment_cancel.setOnClickListener(this);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //如果当前允许存储则 存储当前的评论
                setSaveComStrKey();
            }
        });
        if(dialog.getWindow() == null){
            return;
        }
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setContentView(commentDialogView);
    }


    /**
     * 隐藏dialog
     */
    public void hideDialog() {
        //关闭键盘
        ViewFrameUtils.closeInputSoft(mActivity, commentEdit);
        if (this.dialog != null) {
            try {
                this.dialog.hide();
            } catch (Exception e) {
            }
        }
        setSaveComStrKey();
    }

    /**
     * 存储评论键
     */
    private void setSaveComStrKey() {
        //如果当前允许存储则 存储当前的评论
        if (mCacheComStr == null) {
            mCacheComStr = new HashMap<String, String>();
        }
        if (isSaveComStr) {
            mCacheComStr.put(mCacheKey, commentMsg);
        }
    }

    /**
     * 退出dialog
     */
    public void dismissDialog() {
        if (this.dialog != null) {
            try {
                this.dialog.dismiss();
                this.dialog = null;
            } catch (Exception e) {
            }
        }
    }

    /**
     * 得到评论内容控件
     *
     * @return
     */
    public EditText getCommentEditView() {
        return commentEdit;
    }


    /**
     * 发表稿子评论（包括稿子评论和稿子评论的回复）
     */
    private void sendComment() {
        if (this.mActivity == null) {
            return;
        }
        if (commentMsg == null || "".equals(commentMsg)) {
            ToastUtils.showText("评论内容不能为空");
            return;
//        } else if (!UserInforManager.getInstance().isLogin()) {
//            //判断是否登陆
//            UserInforManager.getInstance().toLoginPage(this.mActivity);
//            return;
        } else if (TextUtils.isEmpty(newsId)) {
            ToastUtils.showText("评论失败 , 请稍后再试");
            return;
        } else if (TextUtils.equals(mOldNewsid, newsId)
                && TextUtils.equals(commentMsg, mOldNewsComment)
                && !compareTime()) {
            //如果一分钟内对同一篇文章连续发表同样的评论则不允许发表
            ToastUtils.showText("短时间内不能发表重复的评论");
            return;
        }



//        UserInfor userinfo = UserInforManager.getInstance().getUserInfor();
        ParamMap paramMap = new ParamMap();
        paramMap.putEncode("classtype", "1");
        paramMap.putEncode("parentid", "0");
        paramMap.putEncode("tocommentid", "");
        paramMap.putEncode("objectid", newsId);
        paramMap.putEncode("content", commentMsg);


        HttpUtils.addPostRequest(URIContant.ADDCOMMENT, new TypeToken<DataBean>(){}.getType(), mRrequestName, paramMap, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                isSaveComStr = true;
                DialogUtils.getInstance().showProgressDialog(mActivity, "正在发表中...");
                mOldCommentTime = System.currentTimeMillis();//获取当前的发表时间
                if (mCommentListener != null) {
                    mCommentListener.commentStart();
                }
            }

            @Override
            public void onError(VolleyError error) {
                DialogUtils.getInstance().dismissProgressDialog();
                ToastUtils.showText(AppApplication.getInstance().getString(R.string.neterror));
                if (mCommentListener != null) {
                    mCommentListener.commentFail(error);
                }
            }

            @Override
            public void onSuccess(DataBean response) {
                DialogUtils.getInstance().dismissProgressDialog();
                if (response.noError()) {
                    FilmComment filmComment = new FilmComment();
                    filmComment.setfContent(commentMsg);
                    filmComment.setfCommentnick(UserInforManager.getInstance().getUserInfor().getfUsername());
                    filmComment.setfIntime(DateUtils.getStrTime_ymd_hms(System.currentTimeMillis()+""));
                    filmComment.setfCommentphoto(UserInforManager.getInstance().getUserInfor().getfPhoto());
                    setCommentResult(filmComment, mCommentListener);
                } else {
                    ToastUtils.makeText(R.drawable.handle_fail, "评论失败,请稍后再试!");
                }
            }
        });


    }

    /**
     * 设置评论结果
     *
     * @param commentResult
     * @param listener
     */
    private void setCommentResult(FilmComment commentResult, CommentListener listener) {
        isSaveComStr = false;//改变配置不存储评论
        mOldNewsid = newsId;//重置上次发表的文章id
        mOldNewsComment = commentResult.getfContent();//重置发表的内容
        ToastUtils.makeText(R.drawable.handle_success, "评论成功");
        hideDialog();//隐藏dialog
        if (listener != null) {
            listener.commentSuccess(commentResult);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        isSaveComStr = true;
        commentMsg = commentEdit.getText().toString();
        if ("".equals(commentMsg)) {
            commentSend.setEnabled(false);
        } else {
            commentSend.setEnabled(true);
        }
    }

    /**
     * 布局中的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.tv_comment_send://发表评论
                sendComment();
                break;
            case R.id.tv_comment_cancel://取消发表评论
                dismissDialog();
                break;

            case R.id.btn_negative://展示出来的dialog的取消键
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.btn_positive://展示出来的dialog的确定键
                DialogUtils.getInstance().dismissCDialog();
                break;
        }
    }

    /**
     * 比较上次发表的时间看是否允许发送
     *
     * @return
     */
    private boolean compareTime() {
        long currentTime = System.currentTimeMillis();
        //如果两次发表的间隔小于60秒
        if ((currentTime - mOldCommentTime) / 1000 < 60) {
            return false;
        }
        return true;
    }




//    /**
//     * 删除评论的方法
//     *
//     * @param articlId    文章Id
//     * @param commentId   评论Id
//     * @param commentType 几级评论类型
//     */
//    public void deleteComment(String articlId, final String commentId, String commentType, final CommentListener commentListener, String packageName) {
//        if (UserInforManager.getInstance().isLogin()) {
//            ParamMap paramMap = new ParamMap();
//            paramMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
//            paramMap.putEncode("articleId", articlId);
//            paramMap.putEncode("commentId", commentId);
//            paramMap.putEncode("type", commentType);
//            HttpUtils.ParmsMapMD5(paramMap);
//
//            HttpListener<DataBean> deleteListener = new HttpListener<DataBean>() {
//                @Override
//                public void onStart() {
//                    super.onStart();
//                    if (commentListener != null) {
//                        commentListener.commentStart();
//                    }
//                }
//
//                @Override
//                public void onError(VolleyError error) {
//                    if (commentListener != null) {
//                        commentListener.commentFail(error);
//                    }
//                }
//
//                @Override
//                public void onSuccess(DataBean response) {
//                    if (response.noError()) {
//                        if (commentListener != null) {
//                            commentListener.commentSuccess(null);
//                        }
//                    }else{
//                        if(commentListener != null){
//                            commentListener.commentFail(null);
//                        }
//                    }
//                }
//            };
//            HttpUtils.addPostRequest(URIContant.DELETE_COMMENT, new TypeToken<DataBean>() {
//            }.getType(), packageName, paramMap, deleteListener);
//        }
//    }


//    /**
//     * 展示 删除dialog 的方法
//     *
//     * 删除时直接调用这个方法即可，点击事件等已经写好了
//     *
//     *
//     * @param activity
//     * @param currentComment    当前操作的评论类
//     * @param commentListener   评论监听
//     * @param isPost    是帖子还是评论
//     */
//    public void showDeleteDialog(Activity activity,NewsComment currentComment,CommentListener commentListener,boolean isPost) {
//        this.mActivity = activity;
//        this.currentReplyComment = currentComment;
//        this.mCommentListener = commentListener;
//
//        HashMap<String,String> style = new HashMap<>();
//        if(isPost){
//            style.put("title",mActivity.getResources().getString(R.string.post_del_title));
//            style.put("desc",mActivity.getResources().getString(R.string.post_del_msg));
//        }else{
//            style.put("title",mActivity.getResources().getString(R.string.comment_del_title));
//            style.put("desc",mActivity.getResources().getString(R.string.comment_del_msg));
//        }
//
//        style.put("btnPosi",mActivity.getResources().getString(R.string.common_confirm));
//        style.put("btnNega",mActivity.getResources().getString(R.string.common_cancel));
//
//        DialogUtils.getInstance().setOnDialogBtnClick(this);
//        DialogUtils.getInstance().showCustomDialog(activity,style);
//
//
//
//
//
//    }


    @Override
    public void onPositiveClick() {
        DialogUtils.getInstance().dismissCustomDialog();
    }

    @Override
    public void onNegativeClick() {
        DialogUtils.getInstance().dismissCustomDialog();
    }
}
